import React, {useEffect, useState} from 'react'
import { Form, Button, Input, Modal,Upload,message, Row, Col,Card,TreeSelect,Select} from 'antd'
import { connect } from 'umi'
import EditProfessionTable from '../components/EditProfessionTable'
import { getDepartmentUser} from '../../service'
import {getUploadUrl} from '@/utils/upload'
import {UploadOutlined} from '@ant-design/icons';
import SelectUserModal from "@/pages/components/SelectUserModal";
import EditManagesTable from "@/pages/Personnel/Promotion/Management/List/components/EditManagesTable";

const FormItem = Form.Item
const { TextArea } = Input;
const { Option } = Select
const formLayout = {
  labelCol: { span: 7 },
}

const colStyle = {
  xl: 8,
  lg: 8,
  md: 8,
  sm: 8,
  xs: 8,
}

const CreateForm = (props) => {

  const { onSubmit, onCancel,visible,currentUser,global = {},loading } = props;
  const {options = {}} = global;
  const {orgTree = [],jobLevel = []} = options;
  const [form] = Form.useForm();
  const [unitTree, setUnitTree] = useState(orgTree);
  const [userList,setUserList] = useState([]);
  const [userCodeList,setUserCodeList] = useState([]);
  const [fileUploadUrls,setFileUploadUrls] = useState([]);
  const [fileName, setFileName] = useState(null);
  const [tempUnitTree,setTempUnitTree] = useState([]);
  const [userModalVisible, setUserModalVisible] = useState(false);

  useEffect(() => {
    if(currentUser){
      form.setFieldsValue(currentUser);
      let temp = [];
      orgTree.map((item) => {
        item.children.map((it) => {
          temp.push(it)
        });
      });
      setTempUnitTree(temp);
    }
  }, [visible]);

  const fileList = {
    name: 'file',
    multiple: false,
    action: getUploadUrl(),
    data: {name: fileName},
    beforeUpload(file) {
      setFileName(file.name)
    },
    onChange(res) {
      const {status} = res.file;
      if (status === 'done') {
        if (res.file.response.error) {
          message.success(`${res.file.response.error}`);
        } else {
          setFileUploadUrls([...fileUploadUrls,res.file.response ]);
          message.success(`${res.file.name} 文件上传成功`);
        }
      } else if (status === 'error') {
        message.error(`${res.file.name} 文件上传失败`);
      }
    },
    onRemove(info) {
      let urls = fileUploadUrls;
      let index = urls.indexOf(info.url);
      if (index > -1)
        urls.splice(index, 1);
      setFileUploadUrls(urls);
    }
  };

  const onFormCancel = () => {
    form.resetFields();
    setUserList([]);
    setFileUploadUrls([]);
    onCancel()
  };

  const handleSubmit = async () => {
    const fieldsValue = await form.validateFields()
    let temp = fieldsValue.employeeEducation || []
    if(temp.length > 0){
      let isReturn = false;
      temp.forEach(item => {
        item.afterUnitId = item.unitId;
        item.afterUnitName = item.unitname;
        item.afterOrgName = item.orgname;
        item.afterOrgId = item.orgId;
        if(!item.afterUnitId){
          message.error("晋升后部门不能为空！");
          isReturn = true;
        }else if(!item.afterJobId){
          message.error("晋升后岗位不能为空！");
          isReturn = true;
        }else if(!item.afterJobLevelId){
          message.error("晋升后职级不能为空！");
          isReturn = true;
        }
      });
      if (isReturn)
        return
    }else{
      message.error("晋升人员列表不能为空！");
      return;
    }
    let reason = fieldsValue.reason;
    let promotionCode = fieldsValue.promotionCode;
    for (const item of temp) {
      item.reason = reason;
      item.promotionKind = 0;
      item.fileUrlList = fileUploadUrls;
      item.afterJobType = 1;
      item.afterUnitId = item.unitId;
      item.promotionCode = promotionCode;
    }
    form.resetFields();
    setUserList([]);
    setFileUploadUrls([]);
    onSubmit(temp);
  };

  const delSelect = (value) => {
    setUserList(userList.filter(item => item.code!==value));
  };

  const showSelectUserModal = () => {
    setUserModalVisible(true);
  };

  const confirmSelectUser = (infos) => {
    if (infos.length>0) {
      let newPromotions = [...userList];
      infos.forEach(info => {
        if(userList.filter(item => item.oid === info.oid).length<1)
          newPromotions.push(info);
      });
      setUserList(newPromotions);
      form.setFieldsValue({promotion: newPromotions.map(item => item.code)});
      setUserModalVisible(false);
    } else {
      message.error('请选择人员!')
    }
  };

  const cancelSelectUser = () => {
    setUserModalVisible(false);
  };

  const savePerson = (values,isDelete) => {
    if (isDelete)
      form.setFieldsValue({promotion:values.map(item => item.code)});
    setUserList(values);
  };

  const renderContent = () => {
    return (
      <>
        <Row gutter={24}>
          <Col {...colStyle}>
            <FormItem name="name" label="申请人">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="department" label="申请部门">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="jobname" label="申请人岗位">
              <Input disabled={true}/>
            </FormItem>
          </Col>
          <Col {...colStyle}>
            <FormItem name="promotionCode" label="晋升人字文" rules={[{required: true, message: '晋升人字文不能为空！'}]}>
              <Input placeholder="请输入晋升人字文"/>
            </FormItem>
          </Col>
          <Col span={16} style={{display: 'flex'}}>
            <Form.Item labelCol={{span: 4}} style={{width:'80%'}} name='promotion' label="选择晋升人员">
              <Select mode="multiple" placeholder="请选择晋升人员" onDeselect={delSelect}>
                {userList.map(item => (<Option key={item.code} value={item.code}>{item.name}</Option>))}
              </Select>
            </Form.Item>
            <Button style={{marginLeft:'5px'}} onClick={()=>showSelectUserModal()}>添加</Button>
          </Col>
          <Col {...colStyle}>
            <FormItem name="urlIds" label="上传附件" rules={[{required: true, message: '上传附件不能为空！'}]}>
              <Upload {...fileList}>
                <Button>
                  <UploadOutlined/> 点击上传附件
                </Button>
              </Upload>
            </FormItem>
          </Col>
          <Card title="添加晋升人员" bordered={false} className='widthStyle' style={{marginBottom:24}}>
            <FormItem name="employeeEducation">
              {
                <EditProfessionTable userList={userList} jobLevel={jobLevel} onChange={savePerson} tempUnitTree={tempUnitTree}/>
              }
            </FormItem>
          </Card>
          <Col span={24}>
            <FormItem name="reason" labelCol={{span: 2}} label="晋升原因" rules={[{required: true,message: '请输入晋升原因！'}]}>
              <TextArea rows={8} className='widthStyle'/>
            </FormItem>
          </Col>
        </Row>
      </>
    )
  }

  const renderFooter = () => {
    return (
      <>
        <Button onClick={() => onFormCancel()}>取消</Button>
        <Button type="primary" loading={loading} onClick={() => handleSubmit()}>确认</Button>
      </>
    )
  };

  return (
    <Modal
      width={'90%'}
      destroyOnClose
      title="批量专业晋级"
      visible={visible}
      footer={renderFooter()}
      onOk={handleSubmit}
      onCancel={() => onFormCancel()}
      okText="确认"
      cancelText="取消"
    >
      <Form
        {...formLayout}
        form={form}
        style={{ paddingTop: '24px' }}
      >
        {renderContent()}
      </Form>
      <SelectUserModal
        selectType={1}
        visible={userModalVisible}
        handleOk={confirmSelectUser}
        handleCancel={cancelSelectUser}
      />
    </Modal>
  )
};


export default connect(({ user, personnel,global }) => ({
  personnel,
  currentUser: user.currentUser,
  global
}))(CreateForm)
